package com.air.controller;

import com.air.common.constant.WxUrlType;
import com.air.common.entity.AccessTokenEntity;
import com.air.common.util.StrUtils;
import com.air.pojo.AirDevice;
import com.air.pojo.AirTask;
import com.air.pojo.AirUser;
import com.air.pojo.AirWxInfo;
import com.air.service.AirDeviceService;
import com.air.service.AirTaskService;
import com.air.service.AirUserService;
import com.air.common.util.WxUtil;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信登陆
 */
@Controller
@RequestMapping("/wx")
public class WxMegController {
    protected static final org.slf4j.Logger logger = LoggerFactory.getLogger(WxMegController.class);
    @Resource
    private AirUserService airUserService;
    @Resource
    private AirDeviceService airDeviceService;
    @Resource
    private AirTaskService airTaskService;

    /**
     * 登录成功跳转
     * @param request
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView loginSys(HttpSession session,HttpServletRequest request){
        String code = request.getParameter("code");
        if(StringUtils.isBlank(code)){
            return new ModelAndView("redirect:/rest/wx/go", null);
        }

        AirWxInfo airWxInfo = (AirWxInfo)session.getServletContext().getAttribute("wxinfo");
        Map<String,String> params = new HashMap<String,String>();
        params.put("appid",airWxInfo.getAppid());
        params.put("secret",airWxInfo.getSecret());
        params.put("code",code);
        params.put("grant_type","authorization_code");
        AccessTokenEntity accessTokenEntity  =WxUtil.sendRequest(WxUrlType.accessTokenUrl, HttpMethod.GET,params,null, AccessTokenEntity.class);

        Map<String,String> getUserInfoParams = new HashMap<String,String>();
        getUserInfoParams.put("access_token", accessTokenEntity.getAccess_token());
        getUserInfoParams.put("openid", accessTokenEntity.getOpenid());
        getUserInfoParams.put("lang","zh_CN");

        AirUser airUser = WxUtil.sendRequest(WxUrlType.userInfoUrl,HttpMethod.GET,getUserInfoParams,null,AirUser.class);
        if(airUser!=null) {
            if(airUser.getOpenid()!=null) {
                airUserService.addAirUser(airUser);
            }
        }
        request.getSession().setAttribute("airUser",airUser);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("index");
        return mv;
    }

    /**
     * 微信登录
     * @param request
     * @return
     */
    @RequestMapping(value = "/go", method = RequestMethod.GET)
    public String  goWx(HttpServletRequest request){
        AirWxInfo airWxInfo = (AirWxInfo)request.getSession().getServletContext().getAttribute("wxinfo");
        String appidUrl="?appid="+airWxInfo.getAppid()+"&";
        String redirect_uri = "redirect_uri=http://air.semsplus.com/rest/wx/login&";
        String typeUrl ="response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        return "redirect:"+WxUrlType.authorizeUrl+appidUrl+redirect_uri+typeUrl;
    }

    /**
     * 设备设置
     * @param request
     * @return
     */
    @RequestMapping(value = "/settings", method = RequestMethod.GET)
    public ModelAndView Settings(HttpServletRequest request) {
        AirUser airUser =(AirUser)request.getSession().getAttribute("airUser");
        if(airUser==null){
            return new ModelAndView("redirect:/rest/wx/go?goUrl=settings", null);
        }
        ModelAndView mv = new ModelAndView();
        mv.setViewName("settings");
        return mv;
    }
    /**
     * 设备设置
     * @return
     */
    @RequestMapping(value = "/binding", method = RequestMethod.GET)
    public ModelAndView Binding() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("binding");
        return mv;
    }
    /**
     * 售后服务
     * @return
     */
    @RequestMapping(value = "/service", method = RequestMethod.GET)
    public ModelAndView Service() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("service");
        return mv;
    }
    /**
     * 设备监控
     * @return
     */
    @RequestMapping(value = "/monitoring", method = RequestMethod.GET)
    public ModelAndView Monitoring(String uid,HttpSession session,Model model) {
        logger.debug("需要监控UID为："+uid);
        if(uid==null||uid.equals("")){
            return new ModelAndView("redirect:/rest/wx/go", null);
        }
        AirUser airUser = (AirUser)session.getAttribute("airUser");
        //需要在此处查询是否归属
        AirDevice airDevice = airDeviceService.selectByUid(uid,airUser.getOpenid());
        if(airDevice==null){
            ModelAndView mv = new ModelAndView();
            mv.setViewName("index");
            return mv;
        }
        ModelAndView mv = new ModelAndView();
        mv.setViewName("monitoring");
        logger.debug("获得滤网时："+airDevice.getFilter_time());
        int surHour =0;
        if(airDevice.getFilter_time()!=null){
            surHour = 1000-StrUtils.getSurplusHour(airDevice.getFilter_time());
        }
        model.addAttribute("name",airDevice.getDevice_name());
        model.addAttribute("surHour",surHour>0?surHour:0);
        return mv;
    }
     /**
     * 设备监控
     * @return
     */
    @RequestMapping(value = "/remove", method = RequestMethod.GET)
    public ModelAndView Remove(String uid,HttpSession session,Model model) {
        if(uid==null||uid.equals("")){
            return new ModelAndView("redirect:/rest/wx/go", null);
        }
        AirUser airUser = (AirUser)session.getAttribute("airUser");
        AirDevice airDevice = airDeviceService.selectByUid(uid,airUser.getOpenid());
        if(airDevice==null){
            ModelAndView mv = new ModelAndView();
            mv.setViewName("index");
            return mv;
        }
        ModelAndView mv = new ModelAndView();
        model.addAttribute("e",airDevice);
        mv.setViewName("remove");
        return mv;
    }

    /**
     * 定时任务
     * @return
     */
    @RequestMapping(value = "/setTime", method = RequestMethod.GET)
    public ModelAndView setTime(String uid,HttpSession session,Model model) {
        if(uid==null||uid.equals("")){
            return new ModelAndView("redirect:/rest/wx/go", null);
        }
        AirUser airUser = (AirUser)session.getAttribute("airUser");
        AirDevice airDevice = airDeviceService.selectByUid(uid,airUser.getOpenid());
        if(airDevice==null){
            ModelAndView mv = new ModelAndView();
            mv.setViewName("index");
            return mv;
        }
        AirTask airTask = airTaskService.selectByUid(airDevice.getDevice_uid());

        ModelAndView mv = new ModelAndView();
        model.addAttribute("e",airDevice);
        if(airTask!=null){
            model.addAttribute("taskTime",airTask.getTaskTime());
        }else{
            model.addAttribute("taskTime","");
        }

        mv.setViewName("time");
        return mv;
    }



}
